import { downloadFile, requestSDspotMarket } from '@src/api/fetch'
import { CreateAllMainReqParams } from '@src/mainSystem/type'
import dayjs from 'dayjs'
import { MainCodeConfig, MainCodes } from './data'
import { getDdifferenceDate, promisetTimeOut } from '@src/utils/common'
import { yunNao } from '@src/api/yunNao'
import { AsyncRecursion, creatAsyncRecursion } from '@src/utils/asyncRecursion'
import { cloneDeep } from "lodash";
import { priviateAccount, userUnitid, dayBillCode } from "@src/config/accountInfo"
import { getPrivateCommonParams } from '@src/spotMarketPrivateData/data'
import { DomMaskInstance } from '@src/entries/contentScript/utils/DomMask'
import { DomMessageInstance } from '@src/entries/contentScript/utils/DomMessage'

/** 获取对应账号的日账单的code */
export const getDayBillCode = () => {
  return dayBillCode?.[priviateAccount] || ''
}

/** 主系统【我的结算】-【现货市场结算】-【日清算单查询】 */
const getSaveOneSettlementBill = async ({fileMsg, headers, unitid}:{fileMsg:any, headers:HeadersInit, dataDate:string, unitid:string}) => {
  console.log('主系统【我的结算】-【现货市场结算】-【日清算单查询】')
  console.log('getSaveOneSettlementBill', {fileMsg, headers})

  const {attachmentName = ''} = fileMsg || {}

  try {
    const {attachmentId} = fileMsg || {}

    const fileHeaders = cloneDeep(headers) as any
    fileHeaders['Settlement-Env'] = null
    fileHeaders['octet-stream'] = 'true'
    
    // const { getType} = MainCodeConfig[MainCodes.DAY_SETTLEMENT_BILL]
  
    const {data: file, fileName} = await downloadFile(
     "https://pmos.sd.sgcc.com.cn/px-settlement-extnetpublish/billConfirm/downloadFile",
      {
        method: "POST",
        body: JSON.stringify({
                "fileIdList": [attachmentId],
                "oldOrNew": true
              }),
        // credentials: "omit", // 设置集成不需要凭证，不然会报请求跨域
        headers: fileHeaders as HeadersInit
      },
      '',
      true
    )
  
   const saveParams = {
    ...getPrivateCommonParams({thirdId:unitid}),
    itemCode: getDayBillCode(),
    file,
   }
  
   console.log('存储数据：', saveParams)
   await yunNao.saveFile(saveParams, fileName)
   console.log("获取数据存储成功", dayjs().format("YYYY-MM-DD HH:mm:ss"))

   DomMessageInstance.success({content: `${attachmentName} 保存成功`, duration: 15 * 1000})
  } catch(e) {
    console.error(e)
    DomMessageInstance.error({content: `${attachmentName} 保存失败`,  duration: 15 * 1000})
  }
}

// 主系统 日账单
export const getSaveDaySettlementBill = async ({headers, userInfo, certainDate}:CreateAllMainReqParams) => {
  console.log('getSaveDaySettlementBill', {headers, userInfo, certainDate})
  let unitid = userUnitid?.[userInfo?.userName] || ''
  if(unitid !== userUnitid[priviateAccount])  {
    console.error(`此用户不能获取主系统日账单 ${unitid}`)
    return Promise.resolve()
  }

  const nowStr = dayjs().format('HH:mm')
  const {dataDate,dataTime} = MainCodeConfig[MainCodes.DAY_SETTLEMENT_BILL]

  if(dataTime.length && !dataTime.includes(nowStr)) return Promise.resolve()
  const date = certainDate ? certainDate : getDdifferenceDate(dataDate,'month')
  try {
    DomMaskInstance.open(`正在获取 ${date} 的日账单数据...`)

    const viewHeaders = cloneDeep(headers) as any
    viewHeaders['Currentroute'] = `/pxf-settlement-extnet/statementConfirm-SD?billsType=D1&date=`+new Date().getTime()
    
    const data = await requestSDspotMarket(
        "https://pmos.sd.sgcc.com.cn/px-settlement-extnetupload/SeRptPrepublishInfo/querySettlementBill",
        JSON.stringify({
          "billsType": "D1",
           date
         }),
        { headers:viewHeaders }
    )
    const dataList = data?.data?.sort((a:any, b:any) => b?.billTime?.localeCompare(a?.billTime)).slice(0, 999) || [] 

    if(!dataList.length) {
      const errTip = '刷新页面再试 或 交易中心数据未发布！'
      DomMessageInstance.error({content:errTip})
      return Promise.reject(new Error(errTip))
    }

    // 请求对应ReqType的所有数据
    await creatAsyncRecursion(AsyncRecursion, {
      stepAsyncFnParamsList: dataList.map((item:any) => ({fileMsg:item, headers:viewHeaders, dataDate: date, unitid})),
      stepAsyncFn: getSaveOneSettlementBill,
      stepCb: async () => await promisetTimeOut(1000), // 每隔 发出请求，防反爬
      stepAsyncNum: 1,
      errBreak: false
    }).start()

   }catch(e) {
    console.error(e)
  }finally {
    DomMessageInstance.success({content: `<h1> ${date} 日账单获取保存操作结束，请查看对比是否有错漏 </h1>`, duration: 20 * 1000})

    DomMaskInstance.close()
  }
}